package upicgame.article.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import upicgame.article.dao.ArticleDao;
import upicgame.entity.Article;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: upicgame
 * @description: ArticleDao实现类
 * @author: lhq
 * @create: 2020-01-03 09:28
 */
@Repository
public class ArticleDaoImpl implements ArticleDao {
	@Resource
	private SessionFactory sessionFactory;


	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	@Override
	public boolean addArticle(Article article) {
		this.getSession().saveOrUpdate(article);
		System.out.println("增加文章成功");
		return true;
	}

	@Override
	public boolean delArticle(Article article) {
		this.getSession().delete(article);
		System.out.println("删除文章成功");
		return true;
	}

	@Override
	public Article findArticle(Integer id) {
		System.out.println(id);
		String hql = "select new Article(id,title,context) from Article where id = :id";
		System.out.println(hql);
		Article article = (Article) this.getSession().createQuery(hql).setParameter("id",id).uniqueResult();
		System.out.println(article);
		return article;
	}

	@Override
	public boolean updateArticle(Article article) {
		this.getSession().saveOrUpdate(article);
		System.out.println("修改成功");
		return true;
	}

	@Override
	public List findAllArticleByPage(Integer currentPage, Integer size) {
		String hql = "select id,title,context,user.name,user.userType from Article";
		Query query = this.getSession().createQuery(hql);
		query.setFirstResult((currentPage-1)*size);
		query.setMaxResults(size);
		List articles = query.list();
		System.out.println(articles);
		return articles;
	}

	@Override
	public Long totalCount() {
		Query query = this.getSession().createQuery("select count(*) from Article ");
		return (Long)query.uniqueResult();
	}

	@Override
	public List<String> getTitle() {
		Query query = this.getSession().createQuery("select id,title from Article ");
		List list = query.list();
		return list;
	}


}
